package com.link.play.fit.ai.ui.vip

import android.annotation.SuppressLint
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.StyleSpan
import android.widget.Toast
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.android.billingclient.api.ProductDetails
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig.daysCaloriePlan
import com.link.play.fit.ai.RemoteConfig.vipNeedPlanPay
import com.link.play.fit.ai.RemoteConfig.vipProductCaloriePlan
import com.link.play.fit.ai.RemoteConfig.vipProductCaloriePlanYear
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.VipRenewAcLayoutBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache.FIRBASE_SUB_PRODUCT_ID
import com.link.play.fit.ai.kv.AuthCache.SUB_CURRENCY
import com.link.play.fit.ai.kv.AuthCache.SUB_PRICE_VALUE
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.utils.CalendarUtils.calculateEndByStartDate
import com.link.play.fit.ai.utils.DateEx.getCurrentDayOfMonth
import com.link.play.fit.ai.utils.GooglePayUtil
import com.link.play.fit.ai.utils.GooglePayUtil.calculateSavingsPercentageFromStrings
import com.link.play.fit.ai.utils.GooglePayUtil.extractAndCalculateDailyPriceMonthsToDay
import com.link.play.fit.ai.utils.GooglePayUtil.extractAndCalculateDailyPriceToMonth
import com.link.play.fit.ai.utils.GooglePayUtil.google_pay_id
import com.link.play.fit.ai.utils.GooglePayUtil.parsePriceString
import com.link.play.fit.ai.utils.OpenAgreementUtils
import com.link.play.fit.ai.utils.TimeUtils.calculateDaysBetween
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class VipRenewAc : BaseActivity<VipRenewAcLayoutBinding>(VipRenewAcLayoutBinding::inflate) {
    private var yearProduct: ProductDetails? = null

    private var monthsProduct: ProductDetails? = null
    private var yearFormattedPrice = ""
    private var monthFormattedPrice = ""

    private var type = ""
    private var userGuide: UserGuide? = null
    private var isChoseYear = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        type = intent.extras?.getString("buyType").toString()
        "type  $type".d()

        EventBus.getDefault().register(this)
        initData()
        initListener()
        queryProductDetails()
        google_pay_id = vipProductCaloriePlan
//        binding.priceText2.paintFlags = binding.priceText2.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        //EventUtils.event("vip_plan_ac", value = "page")
//        binding.freeText.text = "Save 60%"
    }

    override fun useDefaultImmersive() {
        super.useDefaultImmersive()
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun initData() = with(binding) {
//        priceText.text = getString(
//            R.string.price_day,
//            extractAndCalculateDailyPriceToPlanDays(defaultAppPlanPrice, daysCaloriePlan)
//        )
//        priceText2.text = getString(
//            R.string.price_day,
//            extractAndCalculateDailyPriceToPlanDaysx2(defaultAppPlanPrice, daysCaloriePlan)
//        )
        "vipNeedPlanPay  $vipNeedPlanPay".d()

        termsText.paintFlags = termsText.paintFlags or Paint.UNDERLINE_TEXT_FLAG
        privacyText.paintFlags = privacyText.paintFlags or Paint.UNDERLINE_TEXT_FLAG
        RestoreText.paintFlags = RestoreText.paintFlags or Paint.UNDERLINE_TEXT_FLAG

        lifecycleScope.launch {
            userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
            userGuide?.let {

                val days = "${calculateDaysBetween(getCurrentDayOfMonth(), it.planProductEndTime)}Days"
                val fullText = getString(R.string.the_remaining_days_of, days)
                val spannable = SpannableString(fullText)

                val startIndex = fullText.indexOf(days)
                val endIndex = startIndex + days.length
                spannable.setSpan(
                    StyleSpan(Typeface.BOLD),
                    startIndex,
                    endIndex,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                dayText.text = spannable
            }
        }

    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun initListener() = with(binding) {
        backImg.setOnClickListener {
            finish()
        }
        continueText.setOnClickListener {
            monthsProduct?.let {
                FIRBASE_SUB_PRODUCT_ID = it.productId
                SUB_PRICE_VALUE =
                    parsePriceString(it.oneTimePurchaseOfferDetails?.formattedPrice ?: "0.0")
                SUB_CURRENCY = it.oneTimePurchaseOfferDetails?.priceCurrencyCode.orEmpty()
                GooglePayUtil.launchPurchaseFlow(this@VipRenewAc, productDetails = it)
            }
        }
        termsText.setOnClickListener {
            OpenAgreementUtils.openTerms(this@VipRenewAc)
        }
        privacyText.setOnClickListener {
            OpenAgreementUtils.openPrivacy(this@VipRenewAc)
        }
        RestoreText.setOnClickListener {
            if (isChoseYear) {
                yearProduct?.let {
                    GooglePayUtil.launchPurchaseFlow(this@VipRenewAc, productDetails = it)
                }
            } else {
                monthsProduct?.let {
                    GooglePayUtil.launchPurchaseFlow(this@VipRenewAc, productDetails = it)
                }
            }
        }
        yearLayout.setOnClickListener {
            google_pay_id = vipProductCaloriePlanYear

            isChoseYear = true
            yearLayout.background = getDrawable(R.drawable.bg_vip_style_chose)
            weekLayout.background = getDrawable(R.drawable.bg_style_gray_r5)
            yearChoseImg.setImageResource(R.mipmap.icon_xuanzhong_vip)
            monthChoseImg.setImageResource(R.mipmap.icon_weixuanzhong_vip)

            perText.text = getString(
                R.string.per_year_training_plan, yearFormattedPrice
            )
        }
        yearLayout.callOnClick()
        weekLayout.setOnClickListener {
            isChoseYear = false
            google_pay_id = vipProductCaloriePlan

            yearLayout.background = getDrawable(R.drawable.bg_style_gray_r5)
            weekLayout.background = getDrawable(R.drawable.bg_vip_style_chose)
            yearChoseImg.setImageResource(R.mipmap.icon_weixuanzhong_vip)
            monthChoseImg.setImageResource(R.mipmap.icon_xuanzhong_vip)
            perText.text = getString(
                R.string.per_month_training_plan, monthFormattedPrice
            )
        }

        continueText.setOnClickListener {
            if (isChoseYear) {
                yearProduct?.let {
                    GooglePayUtil.launchPurchaseFlow(this@VipRenewAc, productDetails = it)
                }
            } else {
                monthsProduct?.let {
                    GooglePayUtil.launchPurchaseFlow(this@VipRenewAc, productDetails = it)
                }
            }

        }
    }

    private fun queryProductDetails() = with(binding) {
        // 查询商品
        lifecycleScope.launch {
            monthsProduct = GooglePayUtil.queryProduct(vipProductCaloriePlan, false)
            monthsProduct?.let {
                // 显示商品信息
                "formattedPrice  ${it.oneTimePurchaseOfferDetails?.formattedPrice}".d()
                "name  ${it.name}".d()
                "productId  ${it.productId}".d()
                "priceAmountMicros  ${it.oneTimePurchaseOfferDetails?.priceAmountMicros}".d()
                "priceCurrencyCode  ${it.oneTimePurchaseOfferDetails?.priceCurrencyCode}".d()
                it.oneTimePurchaseOfferDetails?.formattedPrice?.let { k ->
                    monthFormattedPrice = k
                    monthValueText.text = k
                    weeklyValueText.text = getString(
                        R.string.day_week_text,
                        extractAndCalculateDailyPriceMonthsToDay(k)
                    )
                    runCatching {
                        val dem = calculateSavingsPercentageFromStrings(
                            yearFormattedPrice,
                            monthFormattedPrice,
                            12
                        )?.toInt()
                        if (dem != null) {
                            binding.freeText.text = getString(
                                R.string.save_text, "${dem}%"
                            )
                        }
                    }
//                    perText.text = getString(
//                        R.string.per_year_training_plan, k
//                    )
                }
            }
        }

        // 查询商品
        lifecycleScope.launch {
            yearProduct = GooglePayUtil.queryProduct(vipProductCaloriePlanYear, false)
            yearProduct?.let {
                // 显示商品信息
                "formattedPrice  ${it.oneTimePurchaseOfferDetails?.formattedPrice}".d()
                "name  ${it.name}".d()
                "productId  ${it.productId}".d()
                "priceAmountMicros  ${it.oneTimePurchaseOfferDetails?.priceAmountMicros}".d()
                "priceCurrencyCode  ${it.oneTimePurchaseOfferDetails?.priceCurrencyCode}".d()
                it.oneTimePurchaseOfferDetails?.formattedPrice?.let { k ->
                    yearFormattedPrice = k
                    yearlyAverageValueText.text = k
                    yearlyValueText.text = getString(
                        R.string.months_year_text,
                        extractAndCalculateDailyPriceToMonth(k)
                    )
                    perText.text = getString(
                        R.string.per_year_training_plan, k
                    )
                    runCatching {
                        val dem = calculateSavingsPercentageFromStrings(
                            yearFormattedPrice,
                            monthFormattedPrice,
                            12
                        )?.toInt()
                        if (dem != null) {
                            binding.freeText.text = getString(
                                R.string.save_text, "${dem}%"
                            )
                        }
                    }
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: String) {
        if (event == "isAppPurchaseVip") {
            Toast.makeText(this, getString(R.string.Purchase_successful), Toast.LENGTH_SHORT)
                .show()
            lifecycleScope.launch {
                val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                userGuide?.apply {
                    isAppPurchaseVip = true
                    if (planProductEndTime.isEmpty()) {
                        planStartTime = getCurrentDayOfMonth()
                    }

                    planProductEndTime = if (planProductEndTime.isEmpty()) {
                        calculateEndByStartDate(getCurrentDayOfMonth(), if (isChoseYear) 365 else daysCaloriePlan.toLong())
                    } else {
                        calculateEndByStartDate(planProductEndTime, if (isChoseYear) 365 else daysCaloriePlan.toLong())
                    }
                    CloudStore.set(DOC_USER_GUIDE, this)

                    "type  $type".d()
                    if (type == "controlPlan") {
                        EventBus.getDefault().post("flushResult")
                    } else if (type == "controlFg") {
                        EventBus.getDefault().post("flushMain")
                    }
                }
                finish()
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}